//
//  RemainPaymentCalculatorViewController.m
//  Rong360
//
//  Created by tianliwei on 8/2/14.
//  Copyright (c) 2014 tianliwei. All rights reserved.
//
#define AnimationInterval 0.5

#import "RemainPaymentCalculatorViewController.h"
#import "RempayResultViewController.h"
#import "RempayCalculator.h"
#import "LoanCalCell.h"
#import "PreDateCell.h"

@interface RemainPaymentCalculatorViewController ()
@property (nonatomic, strong) CalculatePanelView *calculateView;
@property (nonatomic, strong) UIButton *hsPrevBtn;
@property (nonatomic, strong) NSArray *hsDataSource;
@property (nonatomic, strong) NSArray *titles;
@property (nonatomic, strong) NSArray *subTitles;
@property (nonatomic, strong) UITextField *currentField;

@property (nonatomic, strong) UISegmentedControl *segmentedControl;

@property (nonatomic, strong)UIView *datePickerView;
@property (nonatomic, strong)UIDatePicker *datePicker;
@property (nonatomic, strong)UIToolbar *pickerToolbar;

@property (nonatomic, assign) BOOL bBegin;
@property (nonatomic, assign) NSInteger payIndex;//还款日期index
@property (nonatomic, copy) NSString *payTime;
@property (nonatomic, strong) RempayCalculator *rempayCal;
@end

static NSString *CellIdentifier = @"Cell";
static NSString *PreDateCellIdentifier = @"PreDateCell";

@implementation RemainPaymentCalculatorViewController

- (id)init
{
    self = [super init];
    if (self) {
        // Custom initialization
    }
    return self;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"剩余还款计算器";
    self.titles = @[@"贷款总额",@"贷款期限",@"贷款利率",@"第一次还款日期",@"查询还款日期"];
    self.view.backgroundColor = [UIColor whiteColor];
    self.rempayCal = [[RempayCalculator alloc]init];
	// Do any additional setup after loading the view.
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, UI_NAVIFRAME_HEIGHT - HorizonScrollH - CalculatorViewH)];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = (UI_NAVIFRAME_HEIGHT - HorizonScrollH - CalculatorViewH)/self.titles.count;
    self.tableView.scrollEnabled = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"LoanCalCell" bundle:nil] forCellReuseIdentifier:CellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:@"PreDateCell" bundle:nil] forCellReuseIdentifier:PreDateCellIdentifier];
    [self.view addSubview:self.tableView];
    self.subTitles = @[@"万",@"年",@"%"];
    self.hsDataSource = @[@"基准利率",@"83折",@"85折",@"88折",@"9折",@"95折",@"1.1倍",@"1.2倍"];
    self.horizontalScroller = [[HorizontalScroller alloc]initWithFrame:CGRectMake(0, UI_NAVIFRAME_HEIGHT-220, UI_SCREEN_WIDTH, 40)];
    self.horizontalScroller.hsDelegate = self;
    [self.horizontalScroller setButtonData:self.hsDataSource buttonGap:0 buttonWidth:70 buttonHeight:40 maskWidth:60];
    self.horizontalScroller.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    self.horizontalScroller.layer.borderWidth = .5;
    self.horizontalScroller.hidden = YES;
    [self.view addSubview:self.horizontalScroller];
    
    self.calculateView = [[[NSBundle mainBundle]loadNibNamed:@"CalculatePanelView" owner:self options:NULL]lastObject];
    self.calculateView.Y = UI_NAVIFRAME_HEIGHT-180;
    self.calculateView.delegate = self;
    [self.view addSubview:self.calculateView];
    [self initDatePickerView];
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)calculate{
    
    switch (self.currentField.tag) {
        case 0:
            self.rempayCal.loan = self.currentField.text;
            break;
        case 1:
            self.rempayCal.deadline = self.currentField.text;
            break;
        case 2:
            self.rempayCal.rate = self.currentField.text;
            break;
        default:
            break;
    }

    if (0) {//今后再写
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"对不起，请将选项填写完整" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        [self.rempayCal beginCalculate];
        self.hidesBottomBarWhenPushed = YES;
        RempayResultViewController *loanResultVC = [[RempayResultViewController alloc]initWithResults:self.rempayCal.results];
        [self.navigationController pushViewController:loanResultVC animated:YES];
    }
}

- (void)keyBtnClicked:(UIButton *)sender{
    NSString *currentStr = self.currentField.text;
    switch (sender.tag) {
        case 0:
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
            [self inputNumber:sender.titleLabel.text];
            break;
        case 10:{//"."
            BOOL notDot = ([self.currentField.text rangeOfString:@"."].location == NSNotFound);
            if(notDot){
                currentStr= [currentStr stringByAppendingString:@"."];
                self.currentField.text= currentStr;
            }
            break;
        }
        case 11:{//"C"
            self.currentField.text = @"";
            self.bBegin = YES;
            break;
        }
            
        case 12:{
            [self calculate];
            break;
        }
        default:
            break;
    }
}

#pragma HorizontalScrollerDelegate Method
- (void)horizontalScroller:(HorizontalScroller *)scroller didSelectColumnAtIndex:(NSInteger)index{
    if (self.hsPrevBtn) {
        [self.hsPrevBtn setSelected:NO];
    }
    for (UIButton *btn in scroller.subviews) {
        if (btn.tag == index) {
            [btn setSelected:YES];
            self.hsPrevBtn = btn;
        }
    }
    CGFloat jzll = 0;
    if (self.currentField.tag == 2) {
        jzll = [[Config shareConfig].jizhun_house floatValue];
    }
    
    switch (index) {
        case 0:
            self.currentField.text = [FloatUtil stringFromFloat:jzll];
            break;
        case 1:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.83];
            break;
        case 2:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.85];
            break;
        case 3:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.88];
            break;
        case 4:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.90];
            break;
        case 5:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 0.95];
            break;
        case 6:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 1.1];
            break;
        case 7:
            self.currentField.text = [FloatUtil stringFromFloat:jzll * 1.2];
            break;
        default:
            break;
    }
    
}


- (void)inputNumber:(NSString *)str
{
    
    if([self.currentField.text isEqualToString:@"0"] && [str isEqualToString:@"0"]){
        return;
    }
    if(self.bBegin){
        self.currentField.text= str;
    }else{
        self.currentField.text= [self.currentField.text stringByAppendingString:str];
    }
    self.bBegin= NO;
}
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField{
    switch (textField.tag) {
        case 0:
            self.rempayCal.loan = textField.text;
            break;
        case 1:
            self.rempayCal.deadline = textField.text;
            break;
        case 2:
            self.rempayCal.rate = textField.text;
            break;
        default:
            break;
    }
    [textField setUserInteractionEnabled:NO];//add by tian
    return YES;
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{
    [self cancelPickerViewData];
    switch (textField.tag) {
        case 0:
        case 1:
            self.horizontalScroller.hidden = YES;
            break;
        case 2:
            self.horizontalScroller.hidden = NO;
            break;
        default:
            break;
    }
    self.currentField = textField;
    return YES;
}

- (void)initDatePickerView{
    self.pickerToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 40)];
    [self.pickerToolbar setBarStyle:UIBarStyleDefault];
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelPickerViewData)];
    UIBarButtonItem *flexible = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    UIBarButtonItem *okButton = [[UIBarButtonItem alloc] initWithTitle:@"确定" style:UIBarButtonItemStylePlain target:self action:@selector(savePickerViewData)];
    [self.pickerToolbar setItems:[NSArray arrayWithObjects:cancelButton,flexible,okButton, nil]];
    self.datePicker = [[UIDatePicker alloc]initWithFrame:CGRectMake(0, 40, UI_SCREEN_WIDTH, 180)];
    self.datePicker.date = [NSDate date];
    self.datePicker.timeZone = [NSTimeZone timeZoneWithName:@"GTM+8"]; // 设置时区，中国在东八区
//    self.datePicker.minimumDate = [NSDate dateWithTimeIntervalSinceNow:72 * 60 * 60 * -1]; // 设置最小时间
//    self.datePicker.maximumDate = [NSDate dateWithTimeIntervalSinceNow:72 * 60 * 60]; // 设置最大时间
    self.datePicker.datePickerMode = UIDatePickerModeDate; // 设置样式
    [self.datePicker addTarget:self action:@selector(oneDatePickerValueChanged:) forControlEvents:UIControlEventValueChanged]; // 添加监听器
    self.datePickerView = [[UIView alloc]initWithFrame:CGRectMake(0, UI_NAVIFRAME_HEIGHT, UI_SCREEN_WIDTH, 220)];
    self.datePickerView.backgroundColor = [UIColor whiteColor];
    [self.datePickerView addSubview:self.pickerToolbar];
    [self.datePickerView addSubview:self.datePicker];
    [self.view addSubview:self.datePickerView];
    
    self.rempayCal.payfirstDate = self.datePicker.date;
    self.rempayCal.prepayDate = self.datePicker.date;
    
    self.payTime = [DateUtil stringWithDate:self.datePicker.date];
}

#pragma mark - 实现oneDatePicker的监听方法
- (void)oneDatePickerValueChanged:(UIDatePicker *) sender {
    NSDate *select = [sender date]; // 获取被选中的时间
    if (self.payIndex == 3) {
        self.rempayCal.payfirstDate = select;
    }else if (self.payIndex == 4){
        self.rempayCal.prepayDate = select;
    }
    NSDateFormatter *selectDateFormatter = [[NSDateFormatter alloc] init];
    selectDateFormatter.dateFormat = @"yy-MM-dd"; // 设置日期的格式
    NSString *date= [selectDateFormatter stringFromDate:select]; // 把date类型转为设置好格式的string类型
    self.payTime = date;
}

- (void)cancelPickerViewData{
    [UIView animateWithDuration:AnimationInterval animations:^{
        CGRect frame = self.datePickerView.frame;
        frame.origin.y = UI_NAVIFRAME_HEIGHT;
        self.datePickerView.frame = frame;
    }];
}

- (void)savePickerViewData{
    [UIView animateWithDuration:AnimationInterval animations:^{
        CGRect frame = self.datePickerView.frame;
        frame.origin.y = UI_NAVIFRAME_HEIGHT;
        self.datePickerView.frame = frame;
    }];
    
    int res = [DateUtil compareOneDay:self.rempayCal.payfirstDate withAnotherDay:self.rempayCal.prepayDate];
    if (res == 1) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"您输入的提前还款日期比首次还款日期小，请重新输入" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }else{
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.payIndex inSection:0];
        [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.titles.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3 || indexPath.row == 4) {
        PreDateCell *cell = [tableView dequeueReusableCellWithIdentifier:PreDateCellIdentifier];
        cell.mainLabel.text = self.titles[indexPath.row];
        cell.subLabel.text = self.payTime;
        cell.subLabel.textColor = APPCOLOR;
        return cell;
    }else{
        LoanCalCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        cell.mainLabel.text = self.titles[indexPath.row];
        cell.unitLabel.text = self.subTitles[indexPath.row];
        cell.textField.delegate = self;
        cell.textField.inputView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 1, 1)];
        cell.textField.tag = indexPath.row;
        [cell.textField setUserInteractionEnabled:NO];//add by tian
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 3 || indexPath.row == 4) {
        [self.currentField resignFirstResponder];
        self.payIndex = indexPath.row;
        //日期
        [UIView animateWithDuration:AnimationInterval animations:^{
            CGRect frame = self.datePickerView.frame;
            frame.origin.y = UI_NAVIFRAME_HEIGHT - 220;
            self.datePickerView.frame = frame;
        }];
    }else{
        LoanCalCell *cell = (LoanCalCell *)[tableView cellForRowAtIndexPath:indexPath];
        [cell.textField setUserInteractionEnabled:YES];
        [cell.textField becomeFirstResponder];
    }
}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a story board-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}

 */

@end
